#include "MefoolQDeviceManagerWidget.h"

#include <assert.h>
#include <QtGui/QLayout>

#include "MefoolQDeviceWidget.h"

namespace Mefool
{

MefoolQDeviceManagerWidget::MefoolQDeviceManagerWidget( QWidget* parent, Mefool::DeviceManager* deviceManager )
	:	QFrame(parent), 
		mDeviceManager(deviceManager),
		mDeviceListWidget(NULL),
		mStartStopButton(NULL)
{
	setWindowTitle( "Device Manager" );

	QVBoxLayout* mainLayout = new QVBoxLayout();
	setLayout( mainLayout);

	mDeviceListWidget = new QListWidget( this );
	//mDeviceListWidget->setFrameShape( QFrame::Box );
	mainLayout->addWidget( mDeviceListWidget );

	bool ret = false;
/*	QHBoxLayout* bottomBarLayout = new QHBoxLayout();
	mainLayout->addLayout( bottomBarLayout );

	mStartStopButton = new QPushButton( "Start", this );
	mStartStopButton->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, mStartStopButton->sizePolicy().verticalPolicy() ) );
	bottomBarLayout->addWidget( mStartStopButton );
	bool ret = connect( mStartStopButton, SIGNAL( pressed() ), this, SLOT( startStopButtonPressed() ) );
	assert(ret);
*/
	mTimer = new QTimer(this);
	ret = connect( mTimer, SIGNAL( timeout() ), this, SLOT( onTimerTimeOut() ) );
	assert( ret );
	mTimer->setInterval(0);
	mTimer->start();

	mDeviceManager->addListener(this);
}

MefoolQDeviceManagerWidget::~MefoolQDeviceManagerWidget()
{
	mDeviceManager->removeListener(this);
}

void MefoolQDeviceManagerWidget::onTimerTimeOut()
{
	mDeviceManager->update();
}
/*
void MefoolQDeviceManagerWidget::startStopButtonPressed()
{
}*/

void MefoolQDeviceManagerWidget::onDeviceAdded( DeviceManager* deviceManager, Device* device )
{
	QDeviceWidget* deviceWidget = new QDeviceWidget( this, device );
	deviceWidget->setWindowFlags( Qt::Window );
	deviceWidget->show();
	deviceWidget->resize( 640, 480 );

	updateDeviceListWidget();
}

void MefoolQDeviceManagerWidget::onDeviceRemoved( DeviceManager* deviceManager, Device* device )
{
	updateDeviceListWidget();
	QList<QDeviceWidget*> deviceWidgets = findChildren<QDeviceWidget*>();
	for ( int i=0; i<deviceWidgets.size(); ++i )  
	{
		QDeviceWidget* deviceWidget = deviceWidgets.at(i);
		if ( deviceWidget->getDevice()==device )
			deviceWidget->deleteLater();
	}
}

void MefoolQDeviceManagerWidget::updateDeviceListWidget()
{
	mDeviceListWidget->clear();

	Mefool::Devices devices = mDeviceManager->getDevices();
	for ( std::size_t i=0; i<devices.size(); ++i )
		mDeviceListWidget->addItem( devices[i]->getName().c_str() );
}

}

